﻿using System.Diagnostics;
using System.Security.Principal;
using System.Web;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Security;

namespace Lbb.User.Security
{
    /// <summary>
    /// 权限审核器
    /// </summary>
    /// <author>Chiron</author>
    public static class PermissionVerifier
    {
        /// <summary>
        /// 审核权限
        /// </summary>
        /// <param name="principal">审核对象</param>
        /// <param name="operationName">操作名</param>
        /// <returns></returns>
        public static bool Authorize(IPrincipal principal, string operationName)
        {
            var rv = false;
            try
            {
                var exManager = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();
                rv = exManager.Process(() => Check(principal, operationName), false, "Authorization");
            }
            catch
            {
                try
                {
                    rv = Check(principal, operationName);
                }
                catch
                {
                    rv = false;
                }
            }
            Debugger.Log(0, "Authorization", string.Format("Check permission::operation:{0},user:{1},Authorize:{2}.\n", operationName, principal.Identity.Name, rv));
            return rv;
        }

        private static bool Check(IPrincipal principal, string operationName)
        {
            return EnterpriseLibraryContainer.Current.GetInstance<IAuthorizationProvider>().Authorize(principal, operationName);
        }
        /// <summary>
        /// 审核权限
        /// </summary>
        /// <param name="operationName">操作名</param>
        /// <returns></returns>
        public static bool Authorize(string operationName)
        {
            return HttpContext.Current != null && HttpContext.Current.User != null && Authorize(HttpContext.Current.User, operationName);
        }
    }
}
